include ActionController::Streaming

class Picture < ActiveRecord::Base
  set_primary_key "picture_id"

  belongs_to :catalog,
             :class_name => "Catalog",
             :foreign_key => "catalog_id"
           
  has_many  :comments,
            :class_name => "Comment",
            :foreign_key => "picture_id",
            :dependent => true

  validates_presence_of :name

  validates_inclusion_of :access,
                         :in => [0, 1, 2]
                       
  validates_format_of :content_type, :with => /^image/,
                      :message => "you can only upload pictures",
                      :on => :create                      

  def validate # Additional validation.
    
    unless( @temp_file.nil? )
      if @temp_file.kind_of? StringIO    
        @real_file = Tempfile.new("tmp_picture_file", "wb")
        while not @temp_file.eof? 
          @real_file.write @file.read
        end   

         @temp_file = @real_file # Ensure that @temp_file is actually a file.
      end

      if @temp_file.size > 3 * 1024 * 1024 # Validate the maximum allowed file size.
        error.add_to_base("maximum allowed picture size is 3MB")
        return false
      end
    end
    
  end
  
  def is_accessible?(user_id)
    if(user_id != -1)
      return true if catalog.owner.id == user_id
      return true if access == 1 and catalog.owner.users_given_friendship.find(user_id)
    end
    
    return access == 2    
  end
  
  def set_access(new_access)
    update_attributes(:access => new_access)
  end

  def fix_access
    catalog.set_access_up(access) if catalog.access < access
  end
  
  def file=(incomming_file)
    @temp_file = incomming_file # Store the hybrid object for further use.
        
    puts @temp_file.class
    
    self.content_type = incomming_file.content_type unless( @temp_file.nil? || !@temp_file.kind_of?(Tempfile))   
  end
  
  def after_create    
    if @temp_file     
      FileUtils.cp(@temp_file.path, get_path)
      FileUtils.chmod 0600, get_path
    end    
  end
  
  def after_destroy    
    FileUtils.safe_unlink(get_path)
  end
  
  def get_path
    base_file_name = format("img%08d", self.id)
    return "#{RAILS_ROOT}/image_data/#{catalog.owner.username}/#{base_file_name}"
  end
       
  def validate
    for picture in catalog.pictures
      if picture.name == name and picture != self
        errors.add(:name, " is already taken")
        break
      end
    end
  end
end
